﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
//using Java.Net;
using Xamarin.Forms;

namespace XFAndroidFullScreen.Droid
{
    public class AutoUpdate
    {
        public void run()
        {
            try
            {
                int receivedBytes = 0;
                int totalBytes = 0;
                string dirPath = "/sdcard/xymovie/apk";
                var filePath = Path.Combine(dirPath, "xymovie.apk");

                Stream Ins = SpeechSynthesizer.HttpTransmission.GetHttpResponse("", "https://files.gitee.com/group1/M00/08/8E/PaAvDF0olMOAeNH1AF-H1UKFoso154.apk");

                totalBytes = (int)Ins.Length;
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                else
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
                using (FileStream fos = new FileStream(filePath, FileMode.Create))
                {
                    byte[] buf = new byte[512];

                    do
                    {
                        int numread = Ins.Read(buf, 0, 512);
                        receivedBytes += numread;
                        if (numread <= 0)
                        {
                            break;
                        }
                        fos.Write(buf, 0, numread);

                        //进度条代码
                        //if (progessReporter != null)
                        //{
                        //    DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
                        //    progessReporter.Report(args);
                        //}
                    } while (true);
                }

                //调用下载的文件进行安装
                installApk(filePath);
            }
            catch (Exception ex)
            {
                
            }
           
        }



        private void installApk(string filePath)
        {
            var context = Android.App.Application.Context;
            if (context == null)
                return;
             //通过Intent安装APK文件
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(Android.Net.Uri.Parse("file://" + filePath), "application/vnd.android.package-archive");
            //Android.Net.Uri content_url =Android.Net.Uri.Parse(filePath);
            //intent.SetData(content_url);
            intent.SetFlags(ActivityFlags.NewTask);
            context.StartActivity(intent);
        }


    }
}